﻿using Newtonsoft.Json;
using System.Collections.ObjectModel;
using System.IO;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using YY.Admin.Core;
using YY.Admin.Core.Const;
using YY.Admin.Core.EventBus;
using YY.Admin.Event;
using YY.Admin.Module;
using YY.Admin.Services.Service.Auth;
using YY.Admin.Services.Service.Menu;
using YY.Admin.Views;

namespace YY.Admin.ViewModels
{
    public class MainWindowViewModel : BaseViewModel
    {
        private readonly ISysAuthService _authService;
        private SysUser? _currentUser;

        #region 标签集合
        public ObservableCollection<TabItemModel> OpenTabs { get; } = new ObservableCollection<TabItemModel>();
        private TabItemModel? _selectedTab;
        public TabItemModel? SelectedTab
        {
            get => _selectedTab;
            set
            {
                if (SetProperty(ref _selectedTab, value) && value != null)
                {
                    // 发布事件
                    _eventAggregator.GetEvent<TabSelectedEvent>().Publish(value);

                    if (value.TabSource is MenuItem menuItem && SelectedNavItem == null)
                    {
                        var navItem = NavItems?.Where(it => it.ViewName == "MenuTreeView").FirstOrDefault();
                        if (navItem != null)
                        {
                            if (navItem.AlignBottom)
                            {
                                SelectedBottomNavItem = navItem;
                            }
                            else
                            {
                                SelectedTopNavItem = navItem;
                            }
                        }
                    } else if (value.TabSource is NavItem navItem)
                    {
                        if (navItem.AlignBottom)
                        {
                            SelectedBottomNavItem = navItem;
                        } else
                        {
                            SelectedTopNavItem = navItem;
                        }
                    }

                    // 立即切换Tab，然后异步执行导航  --> 解决切换Tab卡顿的问题
                    _ = NavigateToViewAsync(CommonConst.MAIN_WINDOW_CONTENT_REGION, value.ViewName);

                }
            }
        }

        // 添加 TabControl 关闭事件处理命令
        public DelegateCommand<RoutedEventArgs> TabClosedCommand { get; }
        #endregion

        # region 侧边栏
        public ObservableCollection<NavItem>? NavItems { get; set; }
        public ObservableCollection<NavItem>? TopNavItems { get; set; }
        public ObservableCollection<NavItem>? BottomNavItems { get; set; }

        private NavItem? _selectedNavItem;
        public NavItem? SelectedNavItem
        {
            get => _selectedNavItem;
            set {
                if (SetProperty(ref _selectedNavItem, value) && value != null)
                {
                    // 执行命令（如果有）
                    if (value.Command?.CanExecute(value) == true)
                    {
                        value.Command.Execute(value);
                    }
                }
            }
        }

        private NavItem? _selectedTopNavItem;
        public NavItem? SelectedTopNavItem
        {
            get => _selectedTopNavItem;
            set
            {
                if (SetProperty(ref _selectedTopNavItem, value) && value != null)
                {

                    // 取消底部选中 互斥
                    SelectedBottomNavItem = null;

                    SelectedNavItem = value;
                }
            }
        }

        private NavItem? _selectedBottomNavItem;
        public NavItem? SelectedBottomNavItem
        {
            get => _selectedBottomNavItem;
            set
            {
                if (SetProperty(ref _selectedBottomNavItem, value) && value != null)
                {

                    // 取消顶部选中 互斥
                    SelectedTopNavItem = null;

                    SelectedNavItem = value;
                }
            }
        }
        #endregion

        public MainWindowViewModel(
            ISysAuthService authService,
            ISysMenuService sysMenuService,
            IContainerExtension _container,
            IRegionManager regionManager
            ) : base(_container, regionManager)
        {
            _authService = authService;
            // 订阅用户变更事件
            _currentUser = _authService.CurrentUser;
            _authService.UserChanged += OnUserChanged;

            // 登出命令
            LogoutCommand = new DelegateCommand(LogoutAsync);

            // 初始化Sidebar数据
            InitNavItems();

            // 主题设置命令
            OpenThemeSettingsCommand = new DelegateCommand(OpenThemeSettings);
            ResetThemeSettingsCommand = new DelegateCommand(ResetThemeSettings);
            ApplyThemeSettingsCommand = new DelegateCommand(ApplyThemeSettings);
            SaveThemeSettingsCommand = new DelegateCommand(SaveThemeSettings);
            TabClosedCommand = new DelegateCommand<RoutedEventArgs>(OnTabClosed);
            // 加载初始主题设置
            LoadThemeSettings();

            // 订阅事件
            _eventAggregator.GetEvent<TabSourceSelectedEvent>().Subscribe(OpenOrActivateTab);
        }
        #region 主题
        private bool _isSettingsOpen;
        public bool IsSettingsOpen
        {
            get => _isSettingsOpen;
            set => SetProperty(ref _isSettingsOpen, value);
        }

        // 主题设置相关属性
        private SolidColorBrush _headerBrush = Brushes.White;
        public SolidColorBrush HeaderBrush
        {
            get => _headerBrush;
            set => SetProperty(ref _headerBrush, value);
        }

        private SolidColorBrush _menuBrush = (SolidColorBrush)new BrushConverter().ConvertFrom("#ffffff");
        public SolidColorBrush MenuBrush
        {
            get => _menuBrush;
            set => SetProperty(ref _menuBrush, value);
        }

        private SolidColorBrush _headerBackground = Brushes.White;
        public SolidColorBrush HeaderBackground
        {
            get => _headerBackground;
            set => SetProperty(ref _headerBackground, value);
        }

        private SolidColorBrush _menuBackground = (SolidColorBrush)new BrushConverter().ConvertFrom("#ffffff");
        public SolidColorBrush MenuBackground
        {
            get => _menuBackground;
            set => SetProperty(ref _menuBackground, value);
        }
        // 主题设置命令
        public ICommand OpenThemeSettingsCommand { get; }
        public ICommand ResetThemeSettingsCommand { get; }
        public ICommand ApplyThemeSettingsCommand { get; }
        public ICommand SaveThemeSettingsCommand { get; }

        #endregion
        public SysUser? CurrentUser
        {
            get => _currentUser;
            set => SetProperty(ref _currentUser, value);
        }

        public DelegateCommand LogoutCommand { get; }

        private void InitNavItems()
        {
            NavItems = new ObservableCollection<NavItem>
            {
                new NavItem {
                    Icon = "FileTreeOutline",
                    Name = "菜单",
                    ViewName = "MenuTreeView",
                    Command = new DelegateCommand<NavItem>(it => _ = NavigateToViewAsync(CommonConst.MAIN_WINDOW_SIDEBAR_REGION, it.ViewName))
                },
                new NavItem {
                    Icon = "GamepadVariantOutline",
                    Name = "菜单区域",
                    Command = new DelegateCommand<NavItem>(it => _ = NavigateToViewAsync(CommonConst.MAIN_WINDOW_SIDEBAR_REGION, it.ViewName))
                },
                new NavItem {
                    Icon = "FoodAppleOutline",
                    Name = "Tab区域",
                    Command = new DelegateCommand<NavItem>(OpenOrActivateTab)
                },
                new NavItem {
                    Icon = "AccountCircleOutline",
                    Name = "个人中心",
                    AlignBottom = true,
                    Command = new DelegateCommand<NavItem>(OpenOrActivateTab)
                },
                new NavItem {
                    Icon = "Power",
                    Name = "退出登录",
                    AlignBottom = true,
                    IsActive = false,
                    Command = LogoutCommand
                }
            };
            TopNavItems = new(NavItems.Where(t => !t.AlignBottom));
            BottomNavItems = new(NavItems.Where(t => t.AlignBottom));

            SelectedTopNavItem = TopNavItems.FirstOrDefault();
        }

        private void OnUserChanged(object? sender, SysUser? user)
        {
            CurrentUser = user;
            //// 用户变更时刷新菜单
            //LoadMenuAsync();
        }

        private async Task NavigateToViewAsync(string regionName, string? viewName)
        {
            try
            {
                if (string.IsNullOrEmpty(regionName))
                    return;

                var tcs = new TaskCompletionSource<bool>();

                // 视图为空 或者 视图未在容器中注册
                if (string.IsNullOrEmpty(viewName) || !(_container as IContainerProvider).IsRegistered<object>(viewName))
                {
                    _logger.Error($"视图未注册: {viewName}");
                    _regionManager.RequestNavigate(regionName, "NotFoundView");
                    tcs.SetResult(false);
                    return;
                }

                _logger.Information($"开始后台异步导航到: {viewName}");


                // 在UI线程执行导航（但不在属性设置的调用栈中）
                await Application.Current.Dispatcher.InvokeAsync(() =>
                {
                    _regionManager.RequestNavigate(regionName, viewName,
                        result =>
                        {
                            if (result.Success)
                            {
                                _logger.Information($"导航成功: {viewName}");
                                tcs.SetResult(true);
                            }
                            else
                            {
                                _logger.Error($"导航失败: {viewName}");
                                tcs.SetResult(false);
                            }
                        });
                }, DispatcherPriority.Background); // 使用较低优先级

                await tcs.Task;
            }
            catch (Exception ex)
            {
                _logger.Error($"导航异常: {ex.Message}");
            }
        }

        /// <summary>
        /// 打开或激活一个标签页（若已打开则激活，否则新建）
        /// </summary>
        private void OpenOrActivateTab(TabSource tabSource)
        {
            if (tabSource == null) {
                _logger.Debug("tabSource为空");
                return;
            }

            if (tabSource is MenuItem menuItem) 
            {
                // 检查是否是父级菜单（有子菜单）
                if (menuItem.Children?.Count > 0)
                {
                    _logger.Debug($"跳过父级菜单: {menuItem.Name}，它有 {menuItem.Children.Count} 个子菜单");
                    return;
                }

                // 检查是否有有效的 ViewName
                //if (string.IsNullOrEmpty(menuItem.ViewName))
                //{
                //    _logger.Debug($"菜单没有 ViewName: {menuItem.Name}");
                //    return;
                //}

                _logger.Debug($"点击菜单: {menuItem.Name}, ViewName: {menuItem.ViewName}");
            }

            // 检查标签是否已打开
            var existingTab = OpenTabs.FirstOrDefault(t => t.TabSource == tabSource);
            if (existingTab != null)
            {
                _logger.Debug($"切换到已存在标签: {tabSource.ViewName}");
                SelectedTab = existingTab;
                return;
            }

            // 创建新标签
            var newTab = new TabItemModel
            {
                Header = tabSource.Name,
                Icon = tabSource.Icon,
                IconType = tabSource.IconType,
                ViewName = tabSource.ViewName,
                TabSource = tabSource
            };

            _logger.Debug($"创建新标签: {tabSource.ViewName}");
            OpenTabs.Add(newTab);
            SelectedTab = newTab;
        }

        /// <summary>
        /// TabItem 关闭完成后触发
        /// </summary>
        private void OnTabClosed(RoutedEventArgs args)
        {
            if (args.OriginalSource is TabItemModel tabModel)
            {
                //var tabModel = tabItem.DataContext as TabItemModel;
                if (tabModel != null)
                {
                    _logger.Debug($"标签已关闭: {tabModel.Header}");

                    var viewName = OpenTabs.Count <= 1 ? null : tabModel.ViewName;

                    ClearViewFromRegion(viewName);

                    // 当前Tab是最后一个
                    if (OpenTabs.Count <= 1)
                    {
                        var region = _regionManager.Regions[CommonConst.MAIN_WINDOW_SIDEBAR_REGION];
                        var activeView = region.ActiveViews.FirstOrDefault();
                        if (activeView != null)
                        {
                            var navItem = NavItems?.Where(it => it.ViewName == activeView.GetType().Name).FirstOrDefault();
                            if (navItem != null)
                            {
                                if (navItem.AlignBottom)
                                {
                                    SelectedBottomNavItem = navItem;
                                } else
                                {
                                    SelectedTopNavItem = navItem;
                                }
                            }
                        }
                    }

                    if (tabModel.TabSource is MenuItem menuItem)
                    {
                        // 折叠父节点
                        MenuTreeViewModel.ToggleParents(menuItem, false);

                        // 取消菜单选中
                        menuItem?.IsSelected = false;
                    } else if (tabModel.TabSource is NavItem navItem)
                    {
                        if (navItem == SelectedTopNavItem)
                        {
                            SelectedTopNavItem = null;
                            SelectedNavItem = null;
                        }
                        else if (navItem == SelectedBottomNavItem)
                        {
                            SelectedBottomNavItem = null;
                            SelectedNavItem = null;
                        }
                    }

                    // 从集合中移除标签
                    //var idx = OpenTabs.IndexOf(tabModel);
                    //OpenTabs.Remove(tabModel);

                    //// 如果被选中的标签被关闭，尝试选中邻近的标签
                    //if (SelectedTab == tabModel)
                    //{
                    //    if (OpenTabs.Any())
                    //    {
                    //        var newIndex = Math.Min(idx, OpenTabs.Count - 1);
                    //        SelectedTab = OpenTabs[newIndex];
                    //    }
                    //    else
                    //    {
                    //        SelectedTab = null;
                    //        ClearContentRegion();
                    //    }
                    //}
                }
            }
        }

        private void LogoutAsync()
        {
            var messageBoxResult = HandyControl.Controls.MessageBox.Show(
               $"确定退出登录吗？",
               "确认登出",
           MessageBoxButton.OKCancel,
           MessageBoxImage.Warning);

            if (messageBoxResult != MessageBoxResult.OK) return;

            // 停止定时器
            StopTokenCheckTimer();

            _authService.LogoutAsync();

            // 返回登录窗口
            Application.Current.MainWindow?.Hide();
            var loginWindow = _container.Resolve<LoginWindow>();
            Application.Current.MainWindow = loginWindow;
            loginWindow.Show();

            // 清空区域
            ClearRegion();
        }

        /// <summary>
        /// 从区域中清空视图
        /// </summary>
        /// <param name="viewName"></param>
        private void ClearViewFromRegion(string? viewName = null)
        {
            try
            {
                if (_RegionManager.Regions.ContainsRegionWithName(CommonConst.MAIN_WINDOW_CONTENT_REGION))
                {
                    var region = _RegionManager.Regions[CommonConst.MAIN_WINDOW_CONTENT_REGION];

                    if (string.IsNullOrEmpty(viewName))
                    {
                        region.RemoveAll();
                        _logger.Debug($"从区域移除所有视图: {CommonConst.MAIN_WINDOW_CONTENT_REGION}");
                        return;
                    }

                    // 查找并移除指定的视图
                    var viewToRemove = region.Views.FirstOrDefault(v =>
                    {
                        // 根据视图名称或类型来匹配
                        var viewType = v.GetType();
                        return viewType.Name == viewName || viewType.Name == viewName + "View";
                    });

                    if (viewToRemove != null)
                    {
                        region.Remove(viewToRemove);
                        _logger.Debug($"从区域移除视图: {viewName}");
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"清理视图失败: {ex.Message}");
            }
        }

        #region 主题
        private void OpenThemeSettings()
        {
            // 加载当前应用到预览区
            HeaderBrush = HeaderBackground;
            MenuBrush = MenuBackground;
            IsSettingsOpen = true;
        }

        private void ResetThemeSettings()
        {
            // 重置为默认值
            HeaderBrush = Brushes.White;
            MenuBrush = (SolidColorBrush)new BrushConverter().ConvertFrom("#ffffff");
        }

        private void ApplyThemeSettings()
        {
            // 应用预览效果
            HeaderBackground = HeaderBrush;
            MenuBackground = MenuBrush;
        }

        private void SaveThemeSettings()
        {
            try
            {
                var settings = new ThemeSettings
                {
                    HeaderBackground = HeaderBrush.Color.ToString(),
                    MenuBackground = MenuBrush.Color.ToString()
                };

                // 保存到文件
                var json = JsonConvert.SerializeObject(settings, Formatting.Indented);
                var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "themeSettings.json");
                File.WriteAllText(filePath, json);

                // 关闭设置面板
                IsSettingsOpen = false;

                // 应用最终设置
                ApplyThemeSettings();
                //通知主题变更
                _eventAggregator.GetEvent<ThemeChangedEvent>().Publish(settings);
            }
            catch (Exception ex)
            {
                _logger.Error($"保存主题设置失败: {ex.Message}", ex);
            }
        }

        private void LoadThemeSettings()
        {
            try
            {
                var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "themeSettings.json");
                if (File.Exists(filePath))
                {
                    var json = File.ReadAllText(filePath);
                    var settings = JsonConvert.DeserializeObject<ThemeSettings>(json);

                    if (!string.IsNullOrEmpty(settings.HeaderBackground))
                    {
                        HeaderBackground = new SolidColorBrush(
                            (Color)ColorConverter.ConvertFromString(settings.HeaderBackground));
                    }

                    if (!string.IsNullOrEmpty(settings.MenuBackground))
                    {
                        MenuBackground = new SolidColorBrush(
                            (Color)ColorConverter.ConvertFromString(settings.MenuBackground));
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"加载主题设置失败: {ex.Message}", ex);
            }
        }
        #endregion

    }
}
